package com.nstar.carousel.base
{
	import com.nstar.base.event.AdvanceEvent;
	import com.nstar.carousel.manager.CarouselManager;
	
	import flash.events.MouseEvent;
	
	import mx.events.FlexEvent;
	import mx.modules.Module;
	
	/**
	 * 轮播组件基类-Canvas
	 * 实现轮播组件的基本功能，及数据加载
	 * 
	 * 
	 */ 
	public class CarouselCanvasClass extends Module implements CarouselManager
	{
		public static const NEXT:String = "next";
		public static const PRIOR:String = "prior";
		
		private var _dataProvider:Array;
		
		public var products:ProductsBaseClass;
		
		
		public function CarouselCanvasClass()
		{
			super();
			this.addEventListener(FlexEvent.CREATION_COMPLETE,init);
		}
		
		private function init(event:FlexEvent):void{
			//鼠标滚轮操作
			this.addEventListener(MouseEvent.MOUSE_WHEEL,wheelHandler);
			
			this.setStyle("horizontalAlign","center");
			this.setStyle("verticalAlign","middle");
		}
		
		//验证数据
		private function validate():void{
			if(products==null){
				throw new Error("请设置产品加载器！");
			}
		}
		
		
		private function wheelHandler(event:MouseEvent):void{
			if(event.delta<0){
				nextHandler(null);
			}else{
				priorHandler(null);
			}
		}		
		
		//上一个
		public function priorHandler(event:MouseEvent):void{
			var idx:int = products.selectedIndex;
			idx--;
			if(idx<0) idx =0;
			
			products.selectedIndex = idx;
			this.dispatchEvent(new AdvanceEvent(PRIOR));
		}
		//下一个
		public function nextHandler(event:MouseEvent):void{
			var idx:int = products.selectedIndex;
			idx++;
			if(idx>dataProvider.length-1) idx = dataProvider.length-1;
			products.selectedIndex = idx;
			this.dispatchEvent(new AdvanceEvent(NEXT));
		}		
		
		[Bindable]
		public function set dataProvider(value:Array):void{
			validate();
			this._dataProvider = value;
		}
		
		[Bindable]
		public function get dataProvider():Array{
			return this._dataProvider;
		}
		
		//加载数据
		public function loadDataProvider(value:Array):void{
			this.dataProvider = value;
		}
		
	}
}